package com.shishuo.cdn.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;


public class HttpRequestUtil {
    private static Logger logger = Logger.getLogger(HttpRequestUtil.class); 
	private static String charset = "UTF-8";
	
	/**
	 * 获取request中文参数
	 * 
	 * @param request
	 * @param paramName
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getChineseParameter(HttpServletRequest request,String paramName) throws UnsupportedEncodingException{
		if(StringUtil.isEmpty(request.getParameter(paramName))){
			return null;
		}
		return new String(request.getParameter(paramName).getBytes("iso8859-1"),charset);
	}
    
    /**
     * 获取项目路径
     * @return
     */
	/*public static String getRootPath() {
		String classPath = ServletActionContext.getServletContext().getRealPath("/");
		String rootPath  = "";
		//windows下
		if("\\".equals(File.separator)){   
			rootPath = classPath.replace("/", "\\");
		}
		//linux下
		if("/".equals(File.separator)){   
			rootPath = classPath.replace("\\", "/");
		}
		return rootPath;
	}*/
	
	/**
	 * 获取域名目录
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {
		String path  = "";
		String serverName = request.getServerName();
		if (!StringUtil.isEmpty(serverName)) {
			//windows下
			if("\\".equals(File.separator)){   
				if (serverName.contains("235")) {
					path = "http://"+serverName+":8080/guwen/";
				} else if (serverName.contains("localhost")) {
					path = "http://"+serverName+":8080/guwen/";
				}
			}
			//linux下
			if("/".equals(File.separator)){
				if (serverName.contains("192.168.1.12:8080")) {
					path = "http://"+serverName+":8080/guwen/";
				} else {
					path = "http://gkb.haozhiyuan.com.cn/";
				}
			}
		}
		return path;
	}
	
	/**
	 * 获取完整URL
	 */
	public static String getRequestURL(HttpServletRequest request) {
		if (request == null) {
			return "";
		}
		String url = "";
		
		String host = request.getServerName();//域名
		int port = request.getServerPort();//端口号
		url = host + ":" + port;
		url = url + request.getServletPath();

//		java.util.Enumeration names = request.getParameterNames();
		int i = 0;
		if (!"".equals(request.getQueryString())
				|| request.getQueryString() != null) {
			url = url + "?" + request.getQueryString();
		}

/*		if (names != null) {
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				if (i == 0) {
					url = url + "?";
				} else {
					url = url + "&";
				}
				i++;

				String value = request.getParameter(name);
				if (value == null) {
					value = "";
				}

				url = url + name + "=" + value;
				try {
					// java.net.URLEncoder.encode(url, "ISO-8859");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}*/
		try {
			// String enUrl = java.net.URLEncoder.encode(url, "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return url;
	}
	
    /** 
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址; 
     *  
     * @param request 
     * @return 
     * @throws IOException 
     */  
    public final static String getIpAddress(HttpServletRequest request) throws IOException {  
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址  
        String ip = request.getHeader("X-Forwarded-For");
        if (logger.isInfoEnabled()) {  
            logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);  
        }  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("WL-Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_CLIENT_IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getRemoteAddr();  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);  
                }  
            }  
        } else if (ip.length() > 15) {  
            String[] ips = ip.split(",");  
            for (int index = 0; index < ips.length; index++) {  
                String strIp = (String) ips[index];  
                if (!("unknown".equalsIgnoreCase(strIp))) {  
                    ip = strIp;  
                    break;  
                }  
            }  
        }  
        return ip;  
    }  
}
